var express = require('express');
var router = express.Router();
const { loginService, updateAdminService } = require('../service/adminService')
const { formatResponse, tokenMiddleWare } = require('../utils/tool');
const { ValidationError } = require('../utils/errors');

// 登录
router.post('/login', async function (req, res, next) {
  if(req.body.captcha.toLocaleLowerCase() != req.session.captcha?.toLocaleLowerCase()){
    throw new ValidationError('验证码错误')
  }
  let result = await loginService(req.body)
  if (result.token) {
    res.setHeader('authentication', result.token)
  }
  res.send(formatResponse(0, "登录成功", result.user))
});


// 恢复登录状态

router.get('/whoami', async function (req, res, next) {
  const userInfo = tokenMiddleWare(req.get('Authorization'))
  res.send(formatResponse(0, "恢复登录成功", {
    loginId: userInfo.loginId,
    id: userInfo.id,
    name: userInfo.name
  }))
});

// 修改管理员信息
router.put('/', async function (req, res, next) {
  const user = await updateAdminService(req.body)
  res.send(formatResponse(0, "修改成功", user))
})


module.exports = router;
